package demo.guava;

import java.nio.charset.Charset;
import java.util.UUID;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.titan.core.utils.io.ConsoleUtils;
import com.titan.core.utils.object.ListSet;

/**
 * 布隆过滤器
 *
 * @author 周成功
 *
 */
public class BloomFilterTest {

    public static void main(String[] args) {
        // 定义缓存对象数量
        int expectedInsertions = 10000;

        // Creating the BloomFilter
        // 定义判断类型为String，约束错误率为百分之一。
        BloomFilter<String> bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.forName("UTF-8")), expectedInsertions, 0.01);
        
        // 定义校验器
        ListSet<String> cache = new ListSet<String>();
        
        //Putting elements into the filter
        //A BigInteger representing a key of some sort
        for (int i = 0; i < expectedInsertions; i++) {
            String uuid = UUID.randomUUID().toString();
            bloomFilter.put(uuid);
            cache.add(uuid);
        }
        
        int success = 0;
        int failure = 0;
        for (int i = 0; i < expectedInsertions; i++) {
            String value = ( i%100==0 ) ? cache.get(i) : UUID.randomUUID().toString();
            if( bloomFilter.mightContain(value) ) {
                if( cache.contains(value) ) {
                    success = success + 1;
                } else {
                    failure = failure + 1;
                }
            }
        }
        
        ConsoleUtils.log("success", success);
        ConsoleUtils.log("failure", failure);
    }

}
